package com.xiaomei.manager.web.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;



import javax.servlet.http.HttpServletRequest;

import com.xiaomei.manager.model.User;
import com.xiaomei.manager.web.dto.ActivityStateAndUserDto;
import com.xiaomei.manager.web.dto.req.ActivityRecQueryDto;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaomei.manager.model.Experience;
import com.xiaomei.manager.service.IExperienceService;
import com.xiaomei.manager.utils.Constants;
import com.xiaomei.manager.web.aliyun.OSS.AliyunUpload;
import com.xiaomei.manager.web.dto.req.ExperienceQueryDto;
import com.xiaomei.manager.web.page.Page;

@Controller
@RequestMapping("/experience")
public class ExperienceController {
	 	@Autowired
	    private IExperienceService experiService;
	 	
	 	private Logger logger = Logger.getLogger(ExperienceController.class);
    
	    /**
	     * 获取所有商家的体验券信息
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("experience:view")
	    @RequestMapping()
	    public String list(Model model, ExperienceQueryDto dto, Page<Experience> page) {	    	
	    	experiService.selectByParam(dto, page);	
	    	model.addAttribute("dto", dto);
	        model.addAttribute("page", page);     
	        return "experience/list";
	    }
	    
	    /**
	     * 新增体验券
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("experience:create")
	    @RequestMapping(value = "/create", method = RequestMethod.GET)
	    public String showCreateForm(Model model) {	        
	        model.addAttribute("exp", new Experience());
	        model.addAttribute("op", "新增");
	        return "experience/edit";
	    }

	    @RequiresPermissions("experience:create")
	    @RequestMapping(value = "/create", method = RequestMethod.POST)
	    public String create(Experience exp, @RequestParam("files") MultipartFile[] files , RedirectAttributes redirectAttributes) {
	    	
	    	//获取体验券的ID
	    	Integer backid = experiService.selectMaxID();
	    	Integer id = 0;
	    	if(backid == null){
	    		id = 1;
	    	}else{
	    		id = backid + 1;
	    	}
	    	exp.setId(id);
	    	 if(files != null && files.length > 0){  
		            //循环获取file数组中得文件  
		    		int i ;
		            for(i = 0;i<files.length;i++){  
		                MultipartFile file = files[i];	                
		                String fileName = file.getOriginalFilename();	                
		                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
			 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
			                String finalFileName = "experience/"+id+"/img_"+(i+1)+extention;
			                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
			                if(i == 0){
			                	exp.setActivityPic1(url);
			                }else if(i == 1){
			                	exp.setActivityPic2(url);
			                }else if(i == 2){
			                	exp.setActivityPic3(url);
			                }
			            try{
			                AliyunUpload.getInstance();	                
			                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
			                }catch (Exception e) {
								logger.info("新建体验券异常！");
							}	                  
		                }  
		            } 
		    	}
	    	//插入体验券
			exp.setTicketType("0");
			exp.setBusinessLat(BigDecimal.valueOf(11.11));
			exp.setBusinessLng(BigDecimal.valueOf(111.11));
			exp.setType("1");
	    	exp.setTicketAlreadyCount(0);
		    experiService.createExperience(exp);
	        redirectAttributes.addFlashAttribute("msg", "新增成功");
	        return "redirect:/experience";
	    }
	    
	    /**
	     * 更新体验券
	     * @param id
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("experience:update")
	    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	    public String showUpdateForm(@PathVariable("id") Integer id, Model model) {
	        model.addAttribute("exp", experiService.findOne(id));
	        model.addAttribute("op", "修改");
	        return "experience/edit";
	    }

		/**
		 * 报名管理
		 * @return
		 */
		@RequiresPermissions("experience:update")
		@RequestMapping(value = "/manager")
		public String showExperienceManager(Model model, ActivityRecQueryDto dto, Page<ActivityStateAndUserDto> page) {
			experiService.selectSignupUserByParam(dto, page);
			model.addAttribute("id", dto.getId());
			model.addAttribute("dto", dto);
			model.addAttribute("page", page);
			return "experience/manager";
		}

		/**
		 * 激活报名
		 * @return
		 */
		@RequiresPermissions("experience:update")
		@RequestMapping(value = "/active", method = RequestMethod.GET)
		@ResponseBody
		public String doActive(String userCode, Integer id, Integer op) {
			experiService.doActiveUser(userCode, (int)id, (int)op);
			return "success";
		}


	    @RequiresPermissions("experience:update")
	    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
	    public String update(Experience exp, @RequestParam("files") MultipartFile[] files , @PathVariable("id") Integer id, RedirectAttributes redirectAttributes, HttpServletRequest request){	    		    
	    	if(files != null && files.length > 0){  
	            //循环获取file数组中得文件  
	    		int i ;
	            for(i = 0;i<files.length;i++){  
	                MultipartFile file = files[i];	                
	                String fileName = file.getOriginalFilename();	                
	                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
		 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
		                String finalFileName = "experience/"+id+"/img_"+(i+1)+extention;
		                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
		                if(i == 0){
		                	exp.setActivityPic1(url);
		                }else if(i == 1){
		                	exp.setActivityPic2(url);
		                }else if(i == 2){
		                	exp.setActivityPic3(url);
		                }
		            try{
		                AliyunUpload.getInstance();	                
		                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
		                }catch (Exception e) {
							logger.info("修改体验券失败！");
						}	                  
	                }  
	            } 
	    	}
	    	Experience backExp = experiService.selectExperienceById(id);
	    	exp.setVersion(backExp.getVersion());
	        experiService.updateExperience(exp);
	        redirectAttributes.addFlashAttribute("msg", "修改成功");
	        return "redirect:/experience";
	    }
	    
	    /**
	     * 删除体验券
	     * @param id
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("experience:delete")
	    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	    public String showDeleteForm(@PathVariable("id") Integer id, Model model) {	       
	    	model.addAttribute("exp", experiService.findOne(id));
	        model.addAttribute("op", "删除");
	        return "experience/edit";
	    }

	    @RequiresPermissions("experience:delete")
	    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
	    public String delete(@PathVariable("id") Integer id, RedirectAttributes redirectAttributes) {	       
	        Experience exp = experiService.selectExperienceById(id);
	        if(exp.getActivityPic1()!=null && !exp.getActivityPic1().equals("")){
	        	 AliyunUpload.removeOssObject(exp.getActivityPic1());
	        }else if(exp.getActivityPic2()!=null && !exp.getActivityPic2().equals("")){
	        	AliyunUpload.removeOssObject(exp.getActivityPic2());
	        }else if(exp.getActivityPic3()!=null && !exp.getActivityPic3().equals("")){
	        	AliyunUpload.removeOssObject(exp.getActivityPic3());
	        }
	        experiService.deleteExperience(id);
	        redirectAttributes.addFlashAttribute("msg", "删除成功");
	        return "redirect:/experience";
	    }
	  /*  
	    private boolean saveFile(MultipartFile file ,HttpServletRequest request) {  
	        // 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                // 文件保存路径  
	                String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"  
	                        + file.getOriginalFilename();  
	                // 转存文件  
	                file.transferTo(new File(filePath)); 
	                System.out.print(filePath);
	                return true;  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	        return false;  
	    }  
	    */
	    @InitBinder   
	    public void initBinder(WebDataBinder binder) {   
	        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
	        dateFormat.setLenient(true);   
	        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
	    }
}
